package com.ruoyi.web.controller.system;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.exception.BusinessException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.WcFkCustinfo;
import com.ruoyi.system.service.IWcFkCustinfoService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;

/**
 * 客户信息Controller
 * 
 * @author ruoyi
 * @date 2020-01-20
 */
@Controller
@RequestMapping("/system/wccustinfo")
public class WcFkCustinfoController extends BaseController
{
    private String prefix = "system/wccustinfo";

    @Autowired
    private IWcFkCustinfoService wcFkCustinfoService;

    @RequiresPermissions("system:wccustinfo:view")
    @GetMapping()
    public String wccustinfo()
    {
        return prefix + "/wccustinfo";
    }

    /**
     * 查询客户信息列表
     */
    @RequiresPermissions("system:wccustinfo:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WcFkCustinfo wcFkCustinfo)
    {
        startPage();
        List<WcFkCustinfo> list = wcFkCustinfoService.selectWcFkCustinfoList(wcFkCustinfo);
        return getDataTable(list);
    }

    /**
     * 导出客户信息列表
     */
    @RequiresPermissions("system:wccustinfo:export")
    @Log(title = "客户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WcFkCustinfo wcFkCustinfo)
    {
        List<WcFkCustinfo> list = wcFkCustinfoService.selectWcFkCustinfoList(wcFkCustinfo);
        ExcelUtil<WcFkCustinfo> util = new ExcelUtil<WcFkCustinfo>(WcFkCustinfo.class);
        return util.exportExcel(list, "wccustinfo");
    }

    void writeToLocal(String destination, InputStream input)
            throws IOException {
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(destination);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        downloadFile.close();
        input.close();
    }

    // 导出单条客户信息
    @GetMapping("/customerSingle2Excel")
    @ResponseBody
    public AjaxResult customerSingle2Excel(Long id, HttpServletRequest request)
    {
        WcFkCustinfo wcFkCustinfo = wcFkCustinfoService.selectWcFkCustinfoById(id);
        if(wcFkCustinfo != null) {
            String tempdir = System.getProperty("java.io.tmpdir") + File.separator + System.currentTimeMillis();

            try {
                InputStream inputStream = new ClassPathResource("客户信息申请表.xlsx").getInputStream();
                writeToLocal(tempdir, inputStream);
            } catch (Exception e) {
                throw new BusinessException("读取模板失败");
            }

            String src = tempdir;
            String dest = Global.getDownloadPath() + "客户申请表.xlsx";

            TemplateExportParams params = new TemplateExportParams(src);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("carpp", wcFkCustinfo.getCarpp());
            map.put("carspd", wcFkCustinfo.getCarspd());
            map.put("carpl", wcFkCustinfo.getCarpl());
            map.put("carzdj", wcFkCustinfo.getCarzdj());
            map.put("applymoney", wcFkCustinfo.getApplymoney());

            // 客户姓名
            map.put("custname", wcFkCustinfo.getCustname());
            map.put("idcard", wcFkCustinfo.getIdcard());
            map.put("phone", wcFkCustinfo.getPhone());
            map.put("address", wcFkCustinfo.getAddress());
            map.put("address2", wcFkCustinfo.getAddress2());
            map.put("companyname", wcFkCustinfo.getCompanyname());
            map.put("companyaddress", wcFkCustinfo.getCompanyaddress());
            map.put("companyphone", wcFkCustinfo.getCompanyphone());

            map.put("marriage", wcFkCustinfo.getMarriage());
            map.put("homesize", wcFkCustinfo.getHomesize());
            map.put("hometype", wcFkCustinfo.getHometype());

            map.put("homephone", wcFkCustinfo.getHomephone());
            map.put("gender", wcFkCustinfo.getGender());
            map.put("companylevel", wcFkCustinfo.getCompanylevel());
            map.put("companyworkyear", wcFkCustinfo.getCompanyworkyear());
            map.put("linkmanfirstname", wcFkCustinfo.getLinkmanfirstname());
            map.put("linkmanfirstnhone", wcFkCustinfo.getLinkmanfirstnhone());
            map.put("linkmanrelation", wcFkCustinfo.getLinkmanrelation());
            map.put("linkmanfriendname", wcFkCustinfo.getLinkmanfriendname());
            map.put("linkmanfriendphone", wcFkCustinfo.getLinkmanfriendphone());
            map.put("linkmanguarantorname", wcFkCustinfo.getLinkmanguarantorname());
            map.put("linkmanguarantorphone", wcFkCustinfo.getLinkmanguarantorphone());

            List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
            for (int i = 0; i < 4; i++) {
                Map<String, String> lm = new HashMap<String, String>();
                lm.put("id", i + 1 + "");
                lm.put("zijin", i * 10000 + "");
                lm.put("bianma", "A001");
                lm.put("mingcheng", "设计");
                lm.put("xiangmumingcheng", "EasyPoi " + i + "期");
                lm.put("quancheng", "开源项目");
                lm.put("sqje", i * 10000 + "");
                lm.put("hdje", i * 10000 + "");

                listMap.add(lm);
            }
            map.put("maplist", listMap);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
            if(workbook != null) {
                OutputStream out = null;
                try
                {
                    out = new FileOutputStream(dest);
                    workbook.write(out);
                    return AjaxResult.success("客户申请表.xlsx");
                }
                catch (Exception e)
                {
                    throw new BusinessException("导出Excel失败，请联系网站管理员！");
                }
                finally
                {
                    if (workbook != null)
                    {
                        try
                        {
                            workbook.close();
                        }
                        catch (IOException e1)
                        {
                            e1.printStackTrace();
                        }
                    }
                    if (out != null)
                    {
                        try
                        {
                            out.close();
                        }
                        catch (IOException e1)
                        {
                            e1.printStackTrace();
                        }
                    }
                }
            }
        }

        return null;
    }

    /**
     * 新增客户信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存客户信息
     */
    @RequiresPermissions("system:wccustinfo:add")
    @Log(title = "客户信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WcFkCustinfo wcFkCustinfo)
    {
        return toAjax(wcFkCustinfoService.insertWcFkCustinfo(wcFkCustinfo));
    }

    /**
     * 修改客户信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        WcFkCustinfo wcFkCustinfo = wcFkCustinfoService.selectWcFkCustinfoById(id);
        mmap.put("wcFkCustinfo", wcFkCustinfo);
        return prefix + "/edit";
    }

    /**
     * 修改保存客户信息
     */
    @RequiresPermissions("system:wccustinfo:edit")
    @Log(title = "客户信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WcFkCustinfo wcFkCustinfo)
    {
        return toAjax(wcFkCustinfoService.updateWcFkCustinfo(wcFkCustinfo));
    }

    /**
     * 删除客户信息
     */
    @RequiresPermissions("system:wccustinfo:remove")
    @Log(title = "客户信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(wcFkCustinfoService.deleteWcFkCustinfoByIds(ids));
    }
}
